//
//  UIViewController+Toast.swift
//  rdb-led-banner
//
//  Created by radiobox3 on 2025/4/18.
//

import UIKit
import Toast_Swift

extension UIViewController {
    
    ///弹出提示框
    func toast(message: String, completed: ((_ didTap: Bool) -> Void)?) {
        self.view.makeToast(message, point: CGPoint(x: UIDevice.screenWidth() / 2, y: UIDevice.screenHeight() / 2), title: nil, image: nil, completion: completed)
    }
    
    func toast(on view: UIView?, message: String) {
        view?.makeToast(message, point: CGPoint(x: UIDevice.screenWidth() / 2, y:UIDevice.screenHeight() / 2), title: nil, image: nil, completion: nil)
    }
    
    func showLoading(_ position: ToastPosition = .center) {
        self.view.makeToastActivity(position)
    }
    
    func hidenLoading() {
        self.view.hideToastActivity()
    }
    
    static func getCurrentTopController() -> UIViewController? {
        var topController: UIViewController?
        topController = self.recursion(controller: self.KeyWindow()?.rootViewController)
        return topController
    }
    
    public static func recursion(controller: UIViewController?) -> UIViewController? {
        var resultController: UIViewController? = controller
        if controller?.isKind(of: UINavigationController.self) == true {
            resultController = self.recursion(controller: (controller as! UINavigationController).topViewController)
        } else if controller?.isKind(of: UITabBarController.self) == true {
            resultController = self.recursion(controller: (controller as! UITabBarController).selectedViewController)
        } else if controller?.presentedViewController != nil {
            resultController = self.recursion(controller: controller?.presentedViewController)
        }
        return resultController
    }
    
    public static func KeyWindow() -> UIWindow? {
        let windows = UIApplication.shared.windows
        for window in windows.reversed() {
            if window.isMember(of: UIWindow.self) && window.bounds.equalTo(UIScreen.main.bounds) {
                return window
            }
        }
        return nil
    }
    
    ///分享
    func shareApp() {
    
        let url: URL = URL.init(string: Constants.share_url)!
        let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil)
        // 如果使用iPad，需要指定分享视图的 present 方式
        if let popoverController = activityViewController.popoverPresentationController {
            popoverController.sourceView = self.view // 指定分享视图的源视图
            popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0) // 指定分享视图的源矩形
        }
        self.present(activityViewController, animated: true, completion: nil)
    }
    /// 评论
    func writeReview(){
        if let url: URL = URL.init(string: Constants.writeReview_url) {
            UIApplication.shared.open(url)
        }
    }
}
